<template>
  <a-upload ref="Upload" action="/" :accept="allowAccept" :before-upload="fileChange" :disabled="disabled">
    <slot />
  </a-upload>
</template>

<script lang="ts">
import { Vue, Component, Prop } from 'vue-property-decorator'
import { Upload } from 'ant-design-vue'
import { OssClient } from '@/plugins/axios'

@Component({
  name: 'AdminResourcesVideo',
  layout: 'admin'
})
export default class AdminResourcesVideo extends Vue {
  @Prop({ default: () => [], type: Array }) accepts!: Array<string>
  @Prop({ default: false, type: Boolean }) disabled!: boolean
  /**
   * 当前上传记录的标记
   */
  tempCheckpoint: any = null
  /**
   * 上传客户端数据
   */
  clientData: OssClient | null = null

  get allowAccept () {
    return this.accepts.map(item => `.${item}`).join(',')
  }

  /**
   * 开始上传
   */
  start () {
    const self = this
    // object-key可以自定义为文件名（例如file.txt）或目录（例如abc/test/file.txt）的形式，实现将文件上传至当前Bucket或Bucket下的指定目录。
    const { client, file, fileName } = this.clientData!
    client.multipartUpload(fileName, file, {
      progress (progress: number, tempCheckpoint: any) {
        self.$emit('progress', progress)
        // 断点记录点。浏览器重启后无法直接继续上传，您需要手动触发上传操作。
        self.tempCheckpoint = tempCheckpoint
      },
      partSize: 102400,
      checkpoint: this.tempCheckpoint || undefined
    }).then(() => {
      self.$emit('success', self.clientData?.url)
      self.clear()
    }).catch(({ status }: any) => {
      if (status !== 0) {
        self.error()
      }
    })
  }

  /**
   * 文件改变的时候调用
   */
  fileChange (e: File) {
    this.$emit('start')
    this.$wAxios.$ossClient(e, 'video/').then((clientData: any) => {
      this.clientData = clientData
      this.start()
    }).catch(() => {
      this.error()
    })
    return false
  }

  error () {
    this.$emit('error')
    this.$message.error('网络异常。请重新上传')
    this.clear()
  }

  /**
   * 暂停上传
   */
  stop () {
    const { client } = this.clientData as any
    client.cancel()
  }

  /**
   * 清除选中的图片
   */
  clear () {
    this.tempCheckpoint = null
    this.clientData = null;
    // (this.$refs.Upload as Upload).clearFiles()
  }
}
</script>

<style scoped></style>
